<template>
  <q-markup-table class="narrow" flat bordered dense>
    <thead class="sticky-thead">
      <tr class="bg-primary text-white">
        <th>属性名</th>
        <th class="bg-blue-grey-5">属性值（点击可复制）</th>
      </tr>
    </thead>
    <tbody>
      <template v-for="(prop, field) in props">
        <tr :key="field" v-if="isPropShow(field)">
          <td class="text-primary text-select" :class="$q.dark.isActive ? 'bg-blue-grey-10' : 'bg-blue-1'" style="width: 25%">
            <div class="row no-wrap items-center" @click="toggleProp(prop)">
              {{ getPropName(field) }}
              <q-space />
              <q-icon :name="prop.open ? 'arrow_drop_up' : 'arrow_drop_down'" v-if="prop.open != null && !$isEmpty(getPropValue(field))" />
            </div>
            <CommonTips :tips="getPropTips(field)" maxWidth="250px" />
          </td>
          <td class="q-space ellipsis text-select" @click="copyPropValue(field)">{{ getPropValue(field) }}</td>
        </tr>
      </template>
    </tbody>
  </q-markup-table>
</template>

<script>
import { B } from 'boot/utils'

// 【属性列表】
export default {
  props: {
    props: {
      // 属性定义表：{ 属性变量名: 属性名称或定义：{ name: 属性名称, tips: 属性提示（可为函数）, open: 是否展开（null表示不可切换） } }
      type: Object,
      required: true
    },
    info: {
      // 对象信息
      type: Object,
      required: true
    }
  },

  methods: {
    // 获取属性名称
    getPropName(field) {
      const prop = this.props[field]
      return '　'.repeat(field.split('.').length - 1) + (prop.name || prop)
    },

    // 获取属性值
    getPropValue(field) {
      return this.$getNested(this.info, field)
    },

    // 获取属性提示
    getPropTips(field) {
      const prop = this.props[field]
      const tips = typeof prop.tips === 'function' ? prop.tips(this.getPropValue(field)) : prop.tips
      return `html <p class="text-h6 q-mb-xs">${field}</p><div>${tips || '无说明'}</div>`
    },

    // 判断属性是否显示
    isPropShow(field) {
      if (this.getPropValue(field) === undefined) return false
      const pos = field.lastIndexOf('.')
      if (pos < 0) return true
      const parentField = field.slice(0, pos)
      if (this.props[parentField].open === false) return false
      if (!this.isPropShow(parentField)) return false
      return true
    },

    // 嵌套属性开关
    toggleProp(prop) {
      if (prop.open == null) return
      prop.open = !prop.open
      this.$forceUpdate()
    },

    // 复制属性值
    copyPropValue(field) {
      const value = this.getPropValue(field)
      // console.log(value)
      this.$setClipboardText(typeof value === 'object' ? JSON.stringify(value) : String(value))
      this.$notify(`属性${B(this.getPropName(field))}的值已复制到剪贴板`)
    }
  }
}
</script>
